package com.rapida.pet.core;

import java.util.Iterator;
import java.util.Vector;

/**
 * Created by mm on 2015/1/19.
 */

public class StateMachine<StateType, EventType> {
	private StateType mCurrState;
	private Vector<Item> mStateTable = new Vector<Item>();

	public StateMachine(StateType startState) {
		mCurrState = startState;
	}

	public void append(StateType cs, EventType t, StateType ns, IAction action) {
		mStateTable.add(new Item(cs, t, ns, action));
	}
	
	public void append(StateType cs, EventType t, StateType ns) {
		mStateTable.add(new Item(cs, t, ns, new IAction(){

			public boolean guard() {
				return true;
			}

			public void action() {
			}}));
	}
	
	public interface IAction {
		boolean guard();
		void action();
	}

	public class Item {
		StateType currState, nextState;
		EventType triger;
		IAction action;


		public Item(StateType cs, EventType t, StateType ns, IAction a) {
			currState = cs;
			nextState = ns;
			triger = t;
			action = a;
		}
	}

	public boolean eventTriger(EventType triger) {
		boolean isStateChanged = false;
		Iterator<Item> iter = mStateTable.iterator();
		while (iter.hasNext()) {
			Item item = iter.next();
			if (item.currState == mCurrState && item.triger == triger) {
				if (item.action.guard()) {
					mCurrState = item.nextState;
					item.action.action();
					isStateChanged = true;
				}
				break;
			}
		}
		return isStateChanged;
	}

	public void setCurrentState(StateType state) {
		mCurrState = state;
	}

	public StateType currentState() {
		return mCurrState;
	}
}
